import type { LocaleType } from './config';

import { merge } from 'lodash-es';

export const loadLocalePool: LocaleType[] = [];

export function setHtmlPageLang(locale: LocaleType) {
  document.querySelector('html')?.setAttribute('lang', locale);
}

export function setLoadLocalePool(cb: (loadLocalePool: LocaleType[]) => void) {
  cb(loadLocalePool);
}

export function genMessage(langs: Record<string, Record<string, any>>, prefix = 'lang') {
  const obj: Recordable = {};

  Object.keys(langs).forEach((key) => {
    const langFileModule = langs[key].default;
    let fileName;
    if (key.startsWith('/')) {
      let langIndex = key.indexOf('lang');
      if (langIndex != -1) {
        fileName = key.substring(langIndex + 6 + prefix.length);
        // console.log(fileName);
      }
    } else if (key.startsWith('./')) {
      fileName = key.replace(`./${prefix}/`, '').replace(/^\.\//, '');
      // console.log(fileName)
    }
    const lastIndex = fileName.lastIndexOf('.');
    fileName = fileName.substring(0, lastIndex);
    const keyList = fileName.split('/');
    const moduleName = keyList.shift();
    const objKey = keyList.join('.');

    if (moduleName) {
      let newObj: Recordable = {};
      if (objKey) {
        newObj[moduleName] = {};
        newObj[moduleName][objKey] = langFileModule || {};
        merge(obj, newObj);
      } else {
        newObj[moduleName] = langFileModule || {};
        merge(obj, newObj);
      }
    }
  });
  // console.log('t', obj);
  return obj;
}
